const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
function Promise(executor){
	this.callback = [];
	// 状态
	this.state=PENDING;
	// 状态值
	this.result = undefined;
	// 子函数一般以下划线开头
	const _onChangeStateAndResult = function(state,value){
		if(this.state !== PENDING) return;
		// 设置状态
		this.state = state;
		// 设置状态值
		this.result = value;
		this.callback.forEach(item=>{
			if(this.state === FULFILLED) item.onResolved();
			else item.onRejected();
		})

	}
	try{
		executor(_onChangeStateAndResult.bind(this,FULFILLED),_onChangeStateAndResult.bind(this,REJECTED));
	}catch (err){
		_onChangeStateAndResult.call(this,REJECTED,err);
	}
}
Object.assign(Promise.prototype,{
	// onResolved:成功回调
	// onRejected:失败回调
	then(onResolved,onRejected){
		return new Promise((resolve,reject)=>{
			const _common = function(callback){
				setTimeout(()=>{
					// value是成功回调的返回值
					const value = callback(this.result);
					// value为Promise实例
					if(value instanceof Promise){
						value.then(resolve,reject)
					}else{
						resolve(value);
					}
				})
			}
			if(this.state === FULFILLED) {
				_common.call(this,onResolved);
			}
			else if(this.state === REJECTED) {
				_common.call(this,onRejected);
			}else {
				this.callback.push({
					onResolved:_common.bind(this,onResolved),
					onRejected:_common.bind(this,onRejected)
				})
			}
		})

	},
	catch() {
	}
})
export default Promise;